package com.tf.integrated.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccssoft.m8.common.ccssoft.modules.util.EntityWrapperHandle;
import com.ccssoft.m8.common.web.BaseController;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.tf.integrated.config.Config;
import com.tf.integrated.entity.*;
import com.tf.integrated.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 设备管理接口
 * @author allen
 * @date: 2020年9月14日上午10:56:20
 */
@Api(value = "设备",description="DeviceController")
@RestController
public class DeviceController extends BaseController {
    @Autowired
    private DeviceinfoService<DeviceinfoEntity> deviceService;

    @Autowired
    private ChannelsInfoService<ChannelsInfoEntity> channelService;

    @Autowired
    private ClientInfoService<ClientInfoEntity> clientService;

    @Autowired
    private HttpServletRequest request;

    @ApiOperation("设备")
    @GetMapping("/device/hosts")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public JSONObject getDeviceList() {
        JSONObject returnData = new JSONObject();
        String token = request.getHeader("Client_Token");
        EntityWrapperHandle<DeviceinfoEntity> ew0 = new EntityWrapperHandle<DeviceinfoEntity>();
        if(token!=null){
            EntityWrapperHandle<ClientInfoEntity> ew2 = new EntityWrapperHandle<ClientInfoEntity>();
            ew2.eq("token",token);
            List<ClientInfoEntity> clientList = clientService.selectList(ew2);
            if(clientList!=null&&clientList.size()>0){
                JSONArray devices=JSONArray.parseArray(clientList.get(0).getRelationdevice());
                if(devices!=null&&devices.size()>0){
                    StringBuilder sql= new StringBuilder();
                    for(int i=0;i<devices.size();i++){
                        if(i==devices.size()-1){
                            sql.append("deviceid = '").append(devices.getString(i)).append("'");
                        }else{
                            sql.append("deviceid = '").append(devices.getString(i)).append("' or ");
                        }
                    }
                    ew0.where(sql.toString());
                }else{
                    ew0.eq("id",null);
                }
            }else{
                ew0.eq("id",null);
            }
        }
        int total=0;
        List<DeviceinfoEntity> list = deviceService.selectList(ew0);
        JSONArray jsonArray=new JSONArray();
        HashMap<String,JSONObject> map = new HashMap<>();
        if(list!=null&&list.size()>0){
            total=list.size();
            StringBuilder sql= new StringBuilder();
            for(int i=0;i<list.size();i++){
                if(i==list.size()-1){
                    sql.append("deviceid = '").append(list.get(i).getDeviceid()).append("'");
                }else{
                    sql.append("deviceid = '").append(list.get(i).getDeviceid()).append("' or ");
                }
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("id",list.get(i).getDeviceid());
                jsonObject.put("name",list.get(i).getDevicename());
                jsonObject.put("status",list.get(i).getOnline());
                jsonObject.put("chns",new JSONArray());
                jsonArray.add(jsonObject);
                map.put(list.get(i).getDeviceid(),jsonObject);
            }
            EntityWrapperHandle<ChannelsInfoEntity> ew= new EntityWrapperHandle<ChannelsInfoEntity>();
            ew.where(sql.toString());
            List<ChannelsInfoEntity> channelsInfoEntityList = channelService.selectList(ew);
            if(channelsInfoEntityList!=null&&channelsInfoEntityList.size()>0){
                for(ChannelsInfoEntity channelsInfoEntity:channelsInfoEntityList){
                    JSONObject chn = new JSONObject();
                    chn.put("id",channelsInfoEntity.getChnid());
                    chn.put("status",channelsInfoEntity.getOnline());
                    map.get(channelsInfoEntity.getDeviceid()).getJSONArray("chns").add(chn);
                }
            }
        }
        returnData.put("code",200);
        returnData.put("total",total);
        returnData.put("list",jsonArray);
        return returnData;
    }

    @ApiOperation("设备")
    @GetMapping("/device/stream")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public JSONArray getStreamUrl(@RequestParam Map<String, String> data) {
        JSONArray returnData=new JSONArray();
        if(data!=null&&data.size()>0) {
            String deviceId=data.get("id");
            EntityWrapperHandle<ChannelsInfoEntity> ew0 = new EntityWrapperHandle<ChannelsInfoEntity>();
            ew0.eq("deviceid",deviceId);
            List<ChannelsInfoEntity> list = channelService.selectList(ew0);
            if(list!=null&&list.size()>0) {
                JSONArray array = getDevchn(deviceId);
                HashMap<Integer, Integer> map = getMap(array);
                for (ChannelsInfoEntity tmpchety : list) {
                    tmpchety.setOnline(map.get(tmpchety.getChnid()));
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("realtimemain", tmpchety.getRealtimemain());
                    jsonObject.put("realtimeaux", tmpchety.getRealtimeaux());
                    jsonObject.put("realtimeaistream", tmpchety.getRealtimeaistream());
                    jsonObject.put("online", tmpchety.getOnline());
                    jsonObject.put("chnid", tmpchety.getChnid());
                    returnData.add(jsonObject);
                }
                channelService.updateBatchById(list);
            }
        }
        return returnData;
    }

    private JSONArray getDevchn(String devid) {
        JSONArray array = null;
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-Token", Config.getmCurtoken(devid));
        String body = Config.client(Config.getStarturlpre(devid)+"/camera/status", HttpMethod.GET,null, headers);
        if(isExist(body)) {
            JSONObject jsobj = JSONObject.parseObject(body);
            int code = jsobj.getIntValue("Code");
            if (code == 200) {
                array = jsobj.getJSONArray("Data");
            }
        }
        return array;
    }

    private HashMap<Integer,Integer> getMap(JSONArray array){
        HashMap<Integer,Integer> map =new HashMap<>();
        if(array!=null&&array.size()>0) {
            for (int i = 0; i < array.size(); ++i) {
                JSONObject datajson = array.getJSONObject(i);
                if(datajson.getBoolean("IsOnline")){
                    map.put(Config.getChannelFromId(datajson.getInteger("ChannelNo")),1);
                }else{
                    map.put(Config.getChannelFromId(datajson.getInteger("ChannelNo")),0);
                }
            }
        }
        return map;
    }

    public boolean isExist(String value){
        return value != null && !value.equals("");
    }

}